"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const defines_1 = require("../lib/defines");
const enums_1 = require("../utils/enums");
function join(app) {
    const { socket, rooms: lRooms } = app.locals;
    const { userId } = socket.handshake.query;
    socket.on(defines_1.RequestMethod.join, async function (data, cb) {
        const { room: { classId }, uri } = data;
        const { clientUtils, client } = app.locals;
        const __room = lRooms[classId];
        if (!__room) {
            return cb && cb({ status: 'error', message: 'room not find!' });
        }
        if (!__room.members[userId]) {
            __room.setMember(socket.owner);
        }
        socket.join(classId);
        const pipeline = await clientUtils.createMediaPipeline(client);
        __room.members[userId].pipeline = pipeline;
        if (__room.chatMode === enums_1.ChatModeEnums.BROADCAST && uri) {
            __room.members[userId].player = await clientUtils.createPlayerEndpoint(pipeline, uri);
        }
        const endpoint = await clientUtils.createEndpoint(pipeline);
        __room.members[userId].setEndpoint(userId, endpoint);
        clientUtils.onIceCandidate(endpoint, (iceCandidate) => {
            socket.emit('iceCandidate', {
                iceCandidate,
                member: socket.owner
            });
        });
        if (cb) {
            cb({
                status: 'ok',
                resolve: 'joined',
                members: __room.getMembers(),
                room: __room.json(),
            });
        }
    });
}
exports.default = join;
